/*
 * Created on 12.12.2009
 *
 * (c) Copyright Christian P. Fries, Germany. All rights reserved. Contact: email@christian-fries.de.
 */
package YahooFinance;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import YahooFinance.network.FetchStringDelegate;
import YahooFinance.network.NetworkService;

/**
 * @author Christian Fries
 */
public class YahooQuoteFetcher {

	// KONSTANTEN
	public static final String PARAM_STOCK_PRICE = "stock_price";
	public static final String PARAM_DATE = "stock_price";

	private boolean mWriteToMarketBeanRepo = true;
	private boolean mPrintOutLastUpdate = true;
	private String mStockSymbol;
	private MarketDataBeanRepository mMarketDataBeanRepository;

	public YahooQuoteFetcher(String pStockSymbol,
			boolean pWriteToMarketBeanRepo, boolean pPrintOutLastUpdate,
			MarketDataBeanRepository pMarketDataBeanRepository) {
		this.mPrintOutLastUpdate = pPrintOutLastUpdate;
		this.mWriteToMarketBeanRepo = pWriteToMarketBeanRepo;
		this.mStockSymbol = pStockSymbol;
		this.mMarketDataBeanRepository = pMarketDataBeanRepository;

	}

	public synchronized void getUpdate(String... pReturnParams)
			throws IOException, ParseException {

		// Check if we need to update
		// MarketDataBean dataBean = stocks.get(symbol);
		// if(dataBean != null && System.currentTimeMillis() -
		// dataBean.getLastUpdated() < updateIntervall) return;

		/*
		 * Fetch CSV data from Yahoo. The format codes (f=) are: s=symbol, l1 =
		 * last, c1 = change, d1 = trade day, t1 = trade time, o = open, h =
		 * high, g = low, v = volume
		 */
		String url = ("http://finance.yahoo.com/d/quotes.csv?s="
				+ mStockSymbol + "&f=sl1c1vd1t1ohg&e=.csv");
		
		NetworkService.sharedInstance().getResourceFromUrl(new FetchStringDelegate() {

			@Override
			public void fetchSuccessWithString(String result) {
				try {
					String[] str = new String[0];
					String response = processStockDataResponse(result, str );
					System.out.println(response);
				} catch (NumberFormatException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}

			@Override
			public void fetchFailed() {
				// TODO Auto-generated method stub
				
			}

		}, url, "StockInfo");
		
		return;
	}

	private static Date formatDate(String[] yahooStockInfo)
			throws ParseException {
		Date lDate = new Date(System.currentTimeMillis());
		String sYear = yahooStockInfo[4].split("/")[2].replace("\"", "");
		String sMonth = yahooStockInfo[4].split("/")[0].replace("\"", "");

		if (sMonth.length() == 1) {
			sMonth = "0" + sMonth;
		}

		String sDay = yahooStockInfo[4].split("/")[1].replace("\"", "");

		if (sDay.length() == 1) {
			sDay = "0" + sDay;
		}

		String sHour = yahooStockInfo[5].split(":")[0].replace("\"", "");

		if (sHour.length() == 1) {
			sHour = "0" + sHour;
		}

		String sMin = yahooStockInfo[5].split(":")[1].replace("\"", "")
				.replace("am", "").replace("pm", "");

		if (sMin.length() == 1) {
			sMin = "0" + sMin;
		}

		String sParseDate = sYear + "-" + sMonth + "-" + sDay + " " + sHour
				+ ":" + sMin;

		lDate = new Date(new SimpleDateFormat("yyyy-MM-dd hh:mm").parse(
				sParseDate).getTime());
		return lDate;
	}

	
	private String processStockDataResponse(String pResponse, String... pReturnParams ) throws NumberFormatException, IOException, ParseException{
		MarketDataBean lLastUpdatedMarketDataBean = new MarketDataBean();
		String lReturnStatement = null;
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new StringReader(pResponse));
			String inputLine;
			while ((inputLine = reader.readLine()) != null) {
				String[] yahooStockInfo = inputLine.split(",");
				Date lDate = formatDate(yahooStockInfo);
				lLastUpdatedMarketDataBean.setDate(lDate);
				lLastUpdatedMarketDataBean.setSymbol(yahooStockInfo[0]
						.replaceAll("\"", ""));
				lLastUpdatedMarketDataBean.setPrice(Double
						.valueOf(yahooStockInfo[1]));
				if (!yahooStockInfo[2].equals("N/A")) {
					lLastUpdatedMarketDataBean.setChange(Double
							.valueOf(yahooStockInfo[2]));
				}
				if (!yahooStockInfo[3].equals("N/A")) {
					lLastUpdatedMarketDataBean.setVolume(Double
							.valueOf(yahooStockInfo[3]));
				}
			}
			if (mWriteToMarketBeanRepo) {
				mMarketDataBeanRepository.putToRepo(lLastUpdatedMarketDataBean);
			}
			if (mPrintOutLastUpdate) {
				lReturnStatement = "";
				if (pReturnParams.length == 0) {
					lReturnStatement = "Price: "
							+ lLastUpdatedMarketDataBean.getPrice()
							+ "; Stock:"
							+ lLastUpdatedMarketDataBean.getSymbol()
							+ ";\r\n Time:"
							+ lLastUpdatedMarketDataBean.getDate().toLocaleString();
				} else {
					for (String pReturnParam : pReturnParams) {
						if (pReturnParam.equals(PARAM_STOCK_PRICE)) {
							lReturnStatement = lReturnStatement
									+ lLastUpdatedMarketDataBean.getPrice()
									+ ";";
						}
						if (pReturnParam.equals(PARAM_DATE)) {
							lReturnStatement = lReturnStatement
									+ lLastUpdatedMarketDataBean.getDate()
									+ ";";
						}
					}
				}

			}
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
		return lReturnStatement;
	}
	
	
	
	// getter and setter
	
	public boolean isWritingToMarketBeanRepo() {
		return mWriteToMarketBeanRepo;
	}

	public void writeToMarketBeanRepo(boolean writeToMarketBeanRepo) {
		this.mWriteToMarketBeanRepo = writeToMarketBeanRepo;
	}

	public boolean isPrintingOutLastUpdate() {
		return mPrintOutLastUpdate;
	}

	public void printOutLastUpdate(boolean printOutLastUpdate) {
		this.mPrintOutLastUpdate = printOutLastUpdate;
	}
	
	
	
	
}
